import {UploadOutlined} from '@ant-design/icons';
import {
    ProForm,
    ProFormFieldSet,
    ProFormSelect,
    ProFormText,
    ProFormTextArea,
} from '@ant-design/pro-components';
import {Avatar, Button, Input, message, Radio, Upload} from 'antd';
import React, {useEffect, useState} from 'react';
import useStyles from './index.style';
import {ProFormRadio} from "@ant-design/pro-form/lib";
import {requestConfig} from "@/requestConfig";
import {useModel} from "@umijs/max";
import {updateUser} from "@/services/swagger/user";
import {updateUserUsingPost} from "@/services/api-share-backhend/userController";

// 电话号码验证函数
const validatorPhone = (_, value,callback) => {
    if (value === null || value == undefined) {
        return Promise.resolve();
    }
    const phoneRegex = /^[1-9]\d{9,14}$/; // 定义电话号码的正则表达式，根据需要调整
    if (!phoneRegex.test(value)) {
        return Promise.reject(new Error('请输入有效的电话号码'));
    }
    return Promise.resolve();
};

export type PropTy = {
    datasource: API.UserVO
}


const BaseView: React.FC<PropTy> = (props) => {
    const {initialState} = useModel("@@initialState")
    const {styles} = useStyles();
    // 头像组件 方便以后独立，增加裁剪之类的功能
    const [newAvatar,setNewAvatar]=useState<string>()
    const handleChange = (info: any) => {
        if (info.file.status === 'done') {
            // Assuming the response contains the URL and token of the new avatar
            const { data } = info.file.response;
            setNewAvatar(data);
        } else if (info.file.status === 'error') {
            message.error('更换失败');
        }
    };
    useEffect(() => {
        setNewAvatar(props.datasource?.userAvatar)
    },[props,])
    const AvatarView = () => (
        <>
            <div className={styles.avatar_title}>头像</div>
            <div className={styles.avatar} style={{marginLeft:11}}>
                <Avatar src={newAvatar} size={120}/>
            </div>
            <Upload showUploadList={false}
                    action={`${requestConfig.baseURL}/api/user/upload`}
                    data={{userId:initialState.loginUser.id}}
                    onChange={handleChange}
            >
                <div className={styles.button_view}>
                    <Button>
                        <UploadOutlined/>
                        更换头像
                    </Button>
                </div>
            </Upload>
        </>
    );


    const handleFinish = async (value) => {
        try{
            const {userAccount,...reqParam}=value
            const res=await updateUserUsingPost({...reqParam,id:initialState.loginUser.id})
            if(res.data==null||res.data==undefined){
                message.error(res.message)
            }
            else{
                message.success('更新基本信息成功');
            }
        }catch (e){
            message.error("服务器异常")
        }


    };
    return (
        <div className={styles.baseView}>
            {props.datasource == null ? null : (
                <>
                    <div className={styles.left}>
                        <ProForm
                            layout="vertical"
                            onFinish={handleFinish}
                            submitter={{
                                searchConfig: {
                                    submitText: '更新基本信息',
                                },
                                render: (_, dom) => dom[1],
                            }}
                        >
                            <ProFormText
                                width="md"
                                name="userAccount"
                                label="用户账号"
                                disabled={true}
                                initialValue={props.datasource.userAccount}
                            />
                            <ProFormText
                                width="md"
                                name="email"
                                label="邮箱"
                                initialValue={props.datasource.eamil}
                                rules={
                                    [
                                        {type: "email", message: "邮箱格式不正确"},]
                                }

                            />

                            <ProFormText
                                width="md"
                                name="userName"
                                label="昵称"
                                initialValue={props.datasource.userName}
                                rules={
                                    [{required: true, message: "请输入昵称"}]
                                }
                            />
                            <ProFormRadio.Group
                                name="gender"
                                label="性别"
                                fieldProps={{
                                    defaultValue: props.datasource.gender
                                }}
                                options={[
                                    {
                                        label: '男',
                                        value: 1,
                                    },
                                    {
                                        label: '女',
                                        value: 0,
                                    }
                                ]}

                            />

                            <ProFormText
                                label="联系电话"
                                name="phoneNumber"
                                initialValue={props.datasource.phoneNumber}
                                rules={[
                                    {
                                        validator: validatorPhone,
                                    },

                                ]}
                            >
                            </ProFormText>
                        </ProForm>
                    </div>
                    <div className={styles.right}>
                        <AvatarView />
                    </div>
                </>
            )}
        </div>
    );
};
export default BaseView;
